﻿using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;

namespace XmppWebTest.Hub
{
    public class WebSocketHandler
    {
        private static ConcurrentDictionary<string, WebSocket> _clients = new();

        public static async Task HandleWebSocketAsync(HttpContext context)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                string clientId = Guid.NewGuid().ToString();
                _clients.TryAdd(clientId, webSocket);
                Console.WriteLine($"WebSocket 客户端 {clientId} 连接成功！");

                // 监听客户端关闭连接
                await ReceiveMessages(webSocket, clientId);
            }
            else
            {
                context.Response.StatusCode = 400;
            }
        }

        private static async Task ReceiveMessages(WebSocket webSocket, string clientId)
        {
            var buffer = new byte[1024 * 4];

            while (webSocket.State == WebSocketState.Open)
            {
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    _clients.TryRemove(clientId, out _);
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Connection closed", CancellationToken.None);
                    Console.WriteLine($"WebSocket 客户端 {clientId} 断开连接！");
                }
            }
        }

        public static async Task SendMessageToAllAsync(string message)
        {
            var buffer = Encoding.UTF8.GetBytes(message);
            var tasks = _clients.Values
                .Where(socket => socket.State == WebSocketState.Open)
                .Select(socket => socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None))
                .ToArray();

            await Task.WhenAll(tasks);
        }
    }
}
